package com.ice.day726.sync.exercise;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import  java.util.*;
/**
 * @Author ice2020x
 * @Date 2022-08-15 13:41
 * @Description:
 */
@Slf4j
public class ExerciseSell {
    public static void main(String[] args) {
        // 模拟多人买票
        TicketWindow ticketWindow = new TicketWindow(10000);

        List<Integer> ticketCounts = new Vector<>();
        List<Thread> list = new ArrayList<>();
        for(int i=0;i<2000;i++){
            Thread thread = new Thread(()->{
                int count =0;
                synchronized(ticketWindow){
                    count = ticketWindow.sell(randomAmount());
                }
                ticketCounts.add(count);
            });
            thread.start();
            list.add(thread);
        }

        for(Thread t :list){
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        int sum = ticketCounts.stream().mapToInt(ExerciseSell::applyAsInt).sum();
        log.debug("卖出去的票数："+sum);
        log.debug("剩余的票数"+ticketWindow.getCount());


    }
    // Random 为线程安全
    static Random random = new Random();
    // 随机 1~5（正整数）
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }

    private static int applyAsInt(Integer c) {
        if (c == null) {
            return 0;
        } else {
            return c;
        }
    }
}
class TicketWindow {
    private int count;
    public TicketWindow(int count) {
        this.count = count;
    }
    public int getCount() {
        return count;
    }

    // 其实也可以在这里加锁
    public int sell(int amount) {
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }
}

